#include "../../muduo/channel.hpp"
#include "../../muduo/socket.hpp"
#include "../../muduo/log.hpp"
#include "../../muduo/connection.hpp"
#include "../../muduo/acceptor.hpp"

std::unordered_map<uint64_t,Muduo::Connection::PtrConnection> _conns;
uint64_t conn_id = 0;
void ConnectionDestroy(const Muduo::Connection::PtrConnection&conn)
{
    _conns.erase(conn->Id());
}

void OnConnected(const Muduo::Connection::PtrConnection&conn)
{
    DLOG("new connection:%p",conn.get());
}


void OnMessage(const Muduo::Connection::PtrConnection& conn,Muduo::Buffer * buf)
{
    DLOG("%s",buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "hello word";
    conn->Send(str.c_str(),str.size());
    conn->Shutdown();
}


Muduo::EventLoop loop;
void NewConnection(int fd)
{
    conn_id++;
    Muduo::Connection::PtrConnection conn(new Muduo::Connection(&loop,conn_id,fd));
    conn->SetMessageCallback(std::bind(OnMessage,std::placeholders::_1,std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy,std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->EnableInactiveRelease(10);
    conn->Established();//就绪初始化
    _conns.insert(std::make_pair(conn_id,conn));
}

int main()
{
    srand(time(nullptr));
    Muduo::Accepter acceptor(&loop,8080);
    acceptor.SetAcceptCallback(std::bind(NewConnection,std::placeholders::_1));
    acceptor.Listen();
    while(true)
    {
        loop.Start();
    }
    return 0;
}
